package com.wing.device.controller.admin;

import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;

import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.device.model.entity.Maintenance;

import com.wing.device.model.entity.MaintenanceExecute;
import com.wing.device.model.entity.MaintenanceType;
import com.wing.device.model.response.MaintenanExecuteDetailVo;
import com.wing.device.model.response.MaintenanceVo;
import com.wing.device.service.DeviceMaintenanceExecuteDetailService;
import com.wing.device.service.DeviceMaintenanceExecuteService;
import com.wing.device.service.DeviceMaintenanceService;

import com.wing.device.service.DeviceMaintenanceTypeService;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.1.0
 * @Author hz
 * @Date 2024-08-19 15:13
 **/
@Validated
@Api(value = "Admin-设备维修任务管理", tags = "#/device/maintenance")
@RestController("maintenanceController")
@RequestMapping("device/admin/maintenance")
@Slf4j
public class DeviceMaintenanceController {

    @Resource
    private DeviceMaintenanceService deviceMaintenanceService;

    @Resource
    private DeviceMaintenanceExecuteService deviceMaintenanceExecuteService;

    private static final String WAITING_REVIEW = "0";

    @Resource
    private DeviceMaintenanceExecuteDetailService deviceMaintenanceExecuteDetailService;

    @Resource
    private DeviceMaintenanceTypeService deviceMaintenanceTypeService;

    @ApiOperation(value = "查询设备维修保养任务列表", notes = "搜索")
    @GetMapping("/list")
    public PageResult<Maintenance> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String departmentSearchMainId,
            String postIdSearchClaim,
            String status,
            String taskNo,
            String createName,
            String deviceNo,
            String claimName,
            String postId
            ){
        Page<Maintenance> pg = new Page<>(page, limit);
        Map map = new HashMap();
        map.put("status", status);
        map.put("taskNo", taskNo);
        map.put("postId", postId);
        map.put("departmentSearchMainId", departmentSearchMainId);
        map.put("postIdSearchClaim", postIdSearchClaim);
        //录入人
        map.put("createName", createName);
        map.put("deviceNo", deviceNo);
        //认领人
        map.put("claimName", claimName);
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        map.put("databaseUser", databaseUser);
        IPage<Maintenance> list = deviceMaintenanceService.pageList4app(pg, map);
        List<Maintenance> records = list.getRecords();
        records.stream().forEach(info->{
            info.setStatusName(MaintenanceEnum.StatusEnum.getNameByCode(info.getStatus()));
            info.setTaskTypeName(MaintenanceEnum.TaskEmum.getNameByCode(info.getTaskType()));
        });
        //关联相关业务属性
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加维保任务", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody Maintenance maintenance) {
        try {
            if (StringUtils.isEmpty(maintenance.getTaskNo())){
                String taskNo = UniqueIdGeneratorUtil.generateUniqueId("SBWB", "yyyyMMdd", 1000, 9999);
                maintenance.setTaskNo(taskNo);
            }
            if (null == maintenance.getModifier()){
                maintenance.setModifier(JwtUtils.getLoginUserId());
                maintenance.setModifierName(JwtUtils.getLoginUsername());
                maintenance.setUpdateTime(LocalDateTime.now());
            }

            if (null != maintenance.getMaintenanceType()){
                MaintenanceType byId = deviceMaintenanceTypeService.getById(maintenance.getMaintenanceType());
                maintenance.setPostId(byId.getPostId());
                maintenance.setDepartmentId(byId.getDepartmentId());
            }
            maintenance.setExamineType(WAITING_REVIEW);
            deviceMaintenanceService.save(maintenance);
            return JsonResult.success("添加成功");
        } catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "修改产品", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody Maintenance maintenance) {
        try {
            Maintenance type = deviceMaintenanceService.getById(maintenance.getId());
            if (ObjectUtil.isEmpty(type)){
                return JsonResult.fail("无效id！");
            }

            if (null != maintenance.getMaintenanceType()){
                MaintenanceType byId = deviceMaintenanceTypeService.getById(maintenance.getMaintenanceType());
                maintenance.setPostId(byId.getPostId());
                maintenance.setDepartmentId(byId.getDepartmentId());
            }
            deviceMaintenanceService.updateById(maintenance);
            return JsonResult.success("修改成功！");
        } catch (Exception e) {
            return JsonResult.fail("修改失败:" + e.getMessage());
        }
    }

    /**
     * 获取维保任务详情信息
     * @param id
     * @return
     */
    @ApiOperation(value = "获取维保任务详情信息", notes = "详情信息")
    @GetMapping("/getMaintenanceById")
    public JsonResult getMaintenanceById(Long id) {
        try {
            Maintenance type = deviceMaintenanceService.getById(id);
            if (ObjectUtil.isEmpty(type)){
                return JsonResult.fail("无效id！");
            }

            String databaseUser = DynamicDataSource.USER_PREFIX;
            if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
                databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
            }

            MaintenanceVo maintenanceVo = deviceMaintenanceService.getMaintenanceBy(id, databaseUser);
            maintenanceVo.setStatusName(MaintenanceEnum.StatusEnum.getNameByCode(maintenanceVo.getStatus()));
            maintenanceVo.setTaskTypeName(MaintenanceEnum.TaskEmum.getNameByCode(maintenanceVo.getTaskType()));
            maintenanceVo.setExamineTypeName(MaintenanceEnum.AduitEnum.getNameByCode(maintenanceVo.getExamineType()));

            //先创建一个假的 到时候在数据了 换成查询数据
            MaintenanceExecute execute = deviceMaintenanceExecuteService.query().eq("task_id", id).one();
            if (ObjectUtil.isNotEmpty(execute)) {
                //获取物料明细
                List<MaintenanExecuteDetailVo> maintenanExecuteDetailVos = deviceMaintenanceExecuteDetailService.selectListByExecuteId(execute.getId());

                BigDecimal totalPic = maintenanExecuteDetailVos.stream().map(info -> {
                    //相乘保留两位小数
                    return ObjectUtil.isNull(info.getOnePrice())?BigDecimal.ZERO:info.getOnePrice().setScale(2, RoundingMode.HALF_UP);
                }).reduce(BigDecimal.ZERO, BigDecimal::add);
                maintenanceVo.setTotalMoney(totalPic);
                maintenanceVo.setMaintenanExecuteDetailVos(maintenanExecuteDetailVos);
            }
            return JsonResult.success(maintenanceVo);
        } catch (Exception e) {
            return JsonResult.fail("详情信息有误:" + e.getMessage());
        }
    }

    /**
     * 认领任务
     * @param id 维保主键id
     * @return
     */
    @ApiOperation(value = "认领维保任务", notes = "认领")
    @PostMapping("/claim")
    public JsonResult claim(Long id) {
        try {
            Maintenance type = deviceMaintenanceService.getById(id);
            if (ObjectUtil.isEmpty(type)){
                return JsonResult.fail("无效id！");
            }
            //如果不是
            if (!type.getStatus().equals(MaintenanceEnum.StatusEnum.DRL.getCode())){
                return JsonResult.fail("该任务已经被认领！");
            }
            deviceMaintenanceService.updateInfoBy(type);
            return JsonResult.success("认领成功！");
        } catch (Exception e) {
            return JsonResult.fail("认领失败:" + e.getMessage());
        }
    }


    /**
     * 审核维保任务
     * @param id 维保主键id
     * @return
     */
    @ApiOperation(value = "审核维保任务", notes = "审核维保任务")
    @PostMapping("/audit")
    public JsonResult audit(Long id,String checkStatus,String remark) {
        Maintenance type = deviceMaintenanceService.getById(id);
        if (ObjectUtil.isEmpty(type)){
            return JsonResult.fail("无效id！");
        }
        if (!type.getExamineType().equals(WAITING_REVIEW)){
            return JsonResult.fail("非待审状态请勿重复审核！");
        }
        if (StringUtils.isNotEmpty(checkStatus) && checkStatus.equals("approve")){
            type.setExamineType("1");
        }else if(StringUtils.isNotEmpty(checkStatus) && checkStatus.equals("reject")){
            type.setExamineType("2");
        }
        if (StringUtils.isNotEmpty(remark)){
            type.setRemark(remark);
        }
        type.setExamineTime(LocalDateTime.now());
        deviceMaintenanceService.updateById(type);
        return JsonResult.success("成功！");
    }

}
